﻿using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using StockModel;
using Utils;
using Utils.Wpf;

namespace StockAnalyst2.Plugins.Visualization.Historical
{
	internal class DetailViewerVM : ViewModelBase, IDisposable
	{
		#region Attributes

		private readonly ExecutionResultStatistics _statistics;
		private readonly ObservableCollection2<Operation> _result;

		#endregion

		#region Properties

		public ObservableCollection<DetailViewerRowVM> Rows { get; private set; }

		#endregion

		#region Public Methods

		public DetailViewerVM(ObservableCollection2<Operation> result, ExecutionResultStatistics statistics)
		{
			_statistics = statistics;

			this.Rows = new ObservableCollection<DetailViewerRowVM>();

			_result = result;
			_result.CollectionChanged += this.Result_CollectionChanged; // Disposed
		}

		#endregion

		#region Event Handlers

		private void Result_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			if (e.Action == NotifyCollectionChangedAction.Add)
			{
				for (int index = 0; index < e.NewItems.Count; index++)
				{
					this.Rows.Add(new DetailViewerRowVM((Operation)e.NewItems[index], _statistics.AccumulatedOperationPartials[index].Y, _statistics.AmountsRequired[index].Y));					
				}
			}
			else if (e.Action == NotifyCollectionChangedAction.Reset)
			{
				this.Rows.Clear();
			}
		}

		#endregion

		#region IDisposable

		protected bool Disposed { get; private set; }

		private void Dispose(bool disposing)
		{
			if (!this.Disposed)
			{
				this.InternalDispose(disposing);
			}

			this.Disposed = true;
		}

		protected virtual void InternalDispose(bool disposing)
		{
			if (disposing)
			{
				_result.CollectionChanged -= this.Result_CollectionChanged;
			}

			// Dispose here only unmanaged objects 
			// Don’t use managed objects here because maybe 
			// they have been finalized already
		}

		public void Dispose()
		{
			this.Dispose(true);
			GC.SuppressFinalize(this);
		}

		~DetailViewerVM()
		{
			this.Dispose(false);
		}

		#endregion
	}
}
